package com.congwulin.wechat.util;

import com.congwulin.wechat.entity.common.TsVO;
import com.congwulin.wechat.mapper.common.TsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class TsDbLoader {


    /**
     * 数据库访问器
     */
    @Autowired
    private TsMapper tsMapper;

    /**
     * 根据表名和主键数组加载时间戳
     *
     * @param ids
     *          主键数组
     * @param tablename
     *          数据库表表名
     * @return 主键与时间戳的映射
     */
    public Map<String,Timestamp> query(String[] ids, String tablename){
        StringBuilder sql = new StringBuilder();
        sql.append(" select  id,ts from ");
        sql.append(tablename);
        sql.append(" where id in (");
        int length = ids.length;
        for (int i = 0; i < length; i++) {
            sql.append("'");
            sql.append(ids[i]);
            sql.append("'");
            if(i < length - 1) {
                sql.append(",");
            }
        }
        sql.append(") and dr=0 ");

        List<TsVO> list = tsMapper.querySql(sql.toString());
        Map<String,Timestamp> index = new HashMap<String,Timestamp>();
        for (TsVO vo : list) {
            index.put(vo.getId(), vo.getTs());
        }
        return index;
    }
}
